<template>
  <div>
    <el-row class="p-10px">
      <template v-for="post in list">
        <el-col :md="24" class="list">
          <el-row>
            <el-col :md="1">
              <i class="fa fa-file-o text-[#ccc]"></i>
            </el-col>
            <el-col :md="19">
              <nuxt-link :to="'/post/detail/' + post.id" class="title">
                <span> {{ post.post_title }} </span>
              </nuxt-link>
            </el-col>
            <el-col :md="4" class="text-right">
              <span class="text-[#ccc]">{{ formatDate(post.published_time) }}</span>
            </el-col>
          </el-row>
        </el-col>
      </template>
    </el-row>
    <el-row>
      <el-col :md="24" class="mt-10">
        <el-pagination layout="prev,next" :total="total" v-model:current-page="page" :page-size="per_page" class="justify-center" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
const props = defineProps({
  category_id: {
    type: String,
    default: '0',
  },
});
const router = useRouter();
const route = useRoute();
const usePostList = usePostListStore();
const category_id = ref(Number(props.category_id));
const list = ref<Post[]>([]);
const page = ref(Number(route.query.page || 1));
const total = ref(1);
const per_page = ref(10);

const fetchData = async (categoryId: number, currentPage: number) => {
  const post_page = await get_post_by_category_client(categoryId, currentPage);
  if (post_page) {
    list.value = post_page.data;
    total.value = post_page.total;
    page.value = Number(post_page.current_page);
    per_page.value = post_page.per_page;
    router.push({
      query: {
        ...router.currentRoute.value.query,
        page: page.value,
      },
    });
    usePostList.list = list.value;
    usePostList.total = total.value;
    usePostList.page = page.value;
    usePostList.per_page = per_page.value;
  }
};
watch([category_id, page], ([newCategoryId, newPage]) => {
  fetchData(newCategoryId, newPage);
});
await fetchData(category_id.value, page.value);
</script>

<style scoped>
.title:hover {
  text-decoration: underline;
  cursor: pointer;
  color: #333;
}
.title {
  color: #333;
  text-decoration: none;
}
.list {
  border-bottom: 1px solid #ccc;
  line-height: 3;
}
</style>
